<template>
  <div>
    <!-- 面包屑导航-->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!--卡片视图 -->
    <el-card>
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input placeholder="请输入内容" v-model="queryParams.query" clearable @clear="getUserList">
            <el-button slot="append" icon="el-icon-search" @click="getUserList"></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="dialogVisible = true">添加用户</el-button>
        </el-col>
      </el-row>
    </el-card>
    <!-- 用户列表 -->
    <el-table :data="userList" border stripe>
      <el-table-column type="index"></el-table-column>
      <el-table-column prop="username" label="姓名"></el-table-column>
      <el-table-column prop="email" label="邮箱"></el-table-column>
      <el-table-column prop="mobile" label="电话"></el-table-column>
      <el-table-column prop="role_name" label="角色"></el-table-column>
      <el-table-column label="状态">
        <template slot-scope="scope">
          <el-switch v-model="scope.row.mg_state" @change="userStateChange(scope.row)"></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button
            type="primary"
            icon="el-icon-edit"
            size="mini"
            @click="editUserDialog(scope.row.id)"
          ></el-button>
          <el-button
            type="danger"
            icon="el-icon-delete"
            size="mini"
            @click="removeUserById(scope.row.id)"
          ></el-button>
          <el-tooltip class="item" effect="dark" content="分配角色" placement="top" :enterable="false">
            <el-button type="warning" icon="el-icon-setting" size="mini"></el-button>
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>
    <!--分页-->
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="queryParams.pagenum"
      :page-sizes="[1, 2, 3, 4]"
      :page-size="queryParams.pagesize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="totalNum"
    ></el-pagination>
    <!--修改用户弹窗-->
    <el-dialog
      title="修改用户"
      :visible.sync="editUserDialogVisible"
      width="50%"
      @closed="editUserFormClosed"
    >
      <el-form :model="editUserForm" :rules="editUserFormRules" ref="editUserFormRef">
        <el-form-item label="用户名">
          <el-input v-model="editUserForm.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editUserForm.email"></el-input>
        </el-form-item>
        <el-form-item label="联系方式" prop="mobile">
          <el-input v-model="editUserForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editUserDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editUser">确 定</el-button>
      </span>
    </el-dialog>
    <!--新增用户弹窗-->
    <el-dialog title="新增用户" :visible.sync="dialogVisible" width="30%" @closed="addUserFormClosed">
      <el-form :model="addUserForm" :rules="addUserFormRules" ref="addUserFormRef">
        <el-form-item label="用户名">
          <el-input v-model="addUserForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addUserForm.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addUserForm.email"></el-input>
        </el-form-item>
        <el-form-item label="联系方式" prop="mobile">
          <el-input v-model="addUserForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
export default {
    data() {
         var checkMails=(rule,value,cb)=>{
                const regEmail = /^\w+@\w+(\.\w+)+$/
                if (regEmail.test(value)) {
                    return cb()
                }
                cb(new Error('请输入合法的邮箱'))
            }
        var checkPhones=(rule,value,cb)=>{
                const regPhone = /^1[34578]\d{9}$/
                if (regPhone.test(value)) {
                    return cb()
                }
                cb(new Error('请输入合法的手机'))
            }           
        return {
            queryParams: {
                query: '',
                pagenum: 1,
                pagesize: 2,
            },
            userList: [],
            totalNum: 0,
            dialogVisible: false,
            addUserForm:{
                username:'',
                password:'',
                email:'',
                mobile:''
            },
            addUserFormRules:{
                username: [
                  { required: true, message: '请输入用户名', trigger: 'blur' },
                  { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
                ],
                  password: [
                  { required: true, message: '请输入密码', trigger: 'blur' },
                  { min: 6, max: 15,message: '密码在6~15个字符之间',trigger: 'blur'}
                ],
                  email: [
                 { required: true, message: '请输入邮箱', trigger: 'blur' } ,
                 { validator:checkMails,message:'请输入合法邮箱',trigger:'blur'}     
                ],
                  mobile: [
                 { required: true, message: '请输入手机号码', trigger: 'blur' },
                 { validator:checkPhones,message:'请输入合法的手机',trigger:'blur'}
                ]
            },
            editUserFormRules:{
                email: [
                 { required: true, message: '请输入邮箱', trigger: 'blur' } ,
                 { validator:checkMails,message:'请输入合法邮箱',trigger:'blur'}     
                ],
                mobile: [
                 { required: true, message: '请输入手机号码', trigger: 'blur' },
                 { validator:checkPhones,message:'请输入合法的手机',trigger:'blur'}
                ]
            },
            editUserDialogVisible:false,
            editUserForm:{}
        }
    },
    created() {
        this.getUserList()
    },
    methods: {
        async getUserList() {
            const { data: res } = await this.$http.get('users', { params: this.queryParams })
            this.userList = res.data.users
            this.totalNum = res.data.total
        },
        handleSizeChange(newSize) {
            this.queryParams.pagesize = newSize
            this.getUserList()
        },
        handleCurrentChange(currentPage) {
            this.queryParams.pagenum = currentPage
            this.getUserList()
        },
        async userStateChange(row) {
            const { data: res } = await this.$http.put(`users/${row.id}/state/${row.mg_state}`)
            if (res.meta.status !== 200) {
                row.mg_state = !row.mg_state
                this.$message.error('状态修改失败')
            }
            this.$message.success('状态修改成功')
        },
        addUserFormClosed(){
            this.$refs.addUserFormRef.resetFields()
        },
        addUser(){
            this.$refs.addUserFormRef.validate(async valid=>{
                if (!valid) {
                    return this.$message.error('请填写正确的用户信息')
                }
                const {data:res} = await this.$http.post("users",this.addUserForm)
                if (res.meta.status!==201) {
                    this.$message.error('添加用户失败')                    
                }
                this.$message.success('添加用户成功')
                this.dialogVisible = false
                this.getUserList()

            })
        },
        async editUserDialog(id){
            const {data:res} = await this.$http.get('users/'+id)
            if (res.meta.status!==200) {
                return this.$message.error("查询患者信息失败")
            }
            this.editUserForm=res.data
            this.editUserDialogVisible=true
        },
        editUserFormClosed(){
            this.$refs.editUserFormRef.resetFields()
        },
        editUser(){
            this.$refs.editUserFormRef.validate(async valid=>{
                if (!valid) {
                    this.$message.error('修改用户失败')
                }
                console.log(this.editUserForm.id)
                const {data:res} = await this.$http.put("users/"+this.editUserForm.id,{
                    email:this.editUserForm.email,
                    mobile:this.editUserForm.mobile
                })
                if (res.meta.status!==200) {
                    return this.$message.error('更新用户信息失败！')
                }
                this.editUserDialogVisible=false
                this.getUserList()
                this.$message.success('更新用户信息成功')
            })
        },
        async removeUserById(id){
            // 弹窗提示
          const confirmResult=await this.$confirm('此操作将永久删除该用户, 是否继续?', '提示',
            {
             confirmButtonText: '确定',
             cancelButtonText: '取消',
             type: 'warning'
             }
         ).catch(err=>err)
         if (confirmResult!=='confirm') {
             return this.$message.info('已经取消删除')
         }
         const {data:res} = await this.$http.delete('users/'+id)
         if (res.meta.status!==200) {
             return this.$message.error('删除用户失败!')
         }
         this.$message.success('删除用户成功')
         this.getUserList()
        }
    },
}
</script>
<style lang="less" scoped></style>>
